package com.diandiansong.app.ui.cart;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.diandiansong.app.alipay.AuthResult;
import com.diandiansong.app.alipay.PayResult;
import com.diandiansong.app.R;
import com.diandiansong.app.entity.PayIndexInfo;
import com.diandiansong.app.entity.WeChatPay;
import com.diandiansong.app.ui.base.BaseAct;
import com.diandiansong.app.ui.index.OederDetail;
import com.diandiansong.app.ui.index.Order;
import com.diandiansong.app.utils.A;
import com.diandiansong.app.wxapi.WXEntryActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

import butterknife.OnClick;
import diandiansong.library.utils.CCallBack;

/**
 * 支付
 */
public class Pay extends BaseAct {

    static String mOrderId;

    public static void start(Context context, String orderId) {
        mOrderId = orderId;
        Intent starter = new Intent(context, Pay.class);
        context.startActivity(starter);
    }

    String mPayMethod;//linepay=线下支付 alipay=支付宝 weixin=微信支付

    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        initTitle("选择支付方式");

        addContentView(R.layout.pay);

        api = WXAPIFactory.createWXAPI(this, WXEntryActivity.APP_ID);
        api.registerApp(WXEntryActivity.APP_ID);
    }


    @OnClick(R.id.go_alipay)
    public void onMGoAlipayClicked() {
        mPayMethod = "alipay";
        pay();
    }

    @OnClick(R.id.go_wechat)
    public void onMGoWechatClicked() {
        mPayMethod = "weixin";
        payWechat();
    }

    @OnClick(R.id.go_cash)
    public void onMGoCashClicked() {
        mPayMethod = "linepay";
        pay();
    }


    private void payWechat() {
        onLoading();
        A.payIndex(mOrderId, mPayMethod, new CCallBack<WeChatPay>() {
            @Override
            public void onSuccess(WeChatPay o) throws Exception {
                onLoaded();
                WeChatPay.Data data = o.getData();

                PayReq req = new PayReq();
                req.appId = data.getAppid();
                req.partnerId = data.getPartnerid();
                req.prepayId = data.getPrepayid();
                req.nonceStr = data.getNoncestr();
                req.timeStamp = data.getTimestamp();
                req.packageValue = data.getPackageX();
                req.sign = data.getSign();
                req.extData = "商品"; // optional
                toast("正在发起微信支付");
                // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                api.sendReq(req);
            }

            @Override
            public void onFailure(int code, String msg) {
                onLoaded();
                toast(msg);
            }
        });
    }


    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    private void pay() {
        onLoading();
        A.payIndex(mOrderId, mPayMethod, new CCallBack<PayIndexInfo>() {
            @Override
            public void onSuccess(PayIndexInfo o) throws Exception {
                onLoaded();
                if (mPayMethod.equals("linepay")) {
                    toast("购买成功");
                    OrderCheck.doFinish();
                    finish();

                } else if (mPayMethod.equals("alipay")) {
                    final String orderInfo = o.getData();
                    Runnable payRunnable = new Runnable() {

                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(getActivity());
                            Map<String, String> result = alipay.payV2(orderInfo, true);
                            Log.i("msp", result.toString());

                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };

                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                onLoaded();
                toast(msg);
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        toast("支付成功");
                        OrderCheck.doFinish();
                        finish();

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        toast("支付失败");
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        toast("授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()));
                    } else {
                        // 其他状态值则为授权失败
                        toast("授权失败" + String.format("authCode:%s", authResult.getAuthCode()));

                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Order.SubFragment.doRefresh();
    }

    public static class Payer {
        public boolean success;

        public Payer(boolean success) {
            this.success = success;
        }
    }

    public static void doPaySuccess() {
        EventBus.getDefault().post(new Payer(true));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void revievePay(Payer payer) {
        if (payer.success) {
            toast("支付成功");
            OrderCheck.doFinish();
            OederDetail.doUpdateStatus("待收货");
            finish();

        } else {
            toast("支付失败");
        }
    }
}
